package com.lvyq.myplayer.ui.fragment.collect

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.collect.PlayCollectAdapter
import com.lvyq.myplayer.common.util.StartActivityUtils
import com.lvyq.myplayer.database.PlayerDatabase
import com.lvyq.myplayer.model.collect.PlayCollectViewModel
import com.lvyq.myplayer.model.collect.PlayCollectViewModelFactory
import com.lvyq.myplayer.parcelable.SongInfoData
import kotlinx.coroutines.launch

/**
 * 文件描述：SongPlayPagerFragment 单曲
 * 作者：lvyq
 * 创建时间：2025-06-19
 * 修改时间：2025-06-19
 */
class SongCollectPagerFragment: Fragment() {
    private lateinit var playCollectAdapter: PlayCollectAdapter

    private val playCollectViewModel: PlayCollectViewModel by viewModels {
        PlayCollectViewModelFactory(PlayerDatabase.getDatabase(requireContext()).playCollectDao())
    }
    private lateinit var commonView:RecyclerView

    var currentPlayLst :ArrayList<SongInfoData>?=null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
       return  initView()
    }

    private fun initView(): View? {
        var view  = View.inflate(context, R.layout.fragment_common_song,null)
        commonView=view.findViewById<RecyclerView>(R.id.commonView)
        commonView.layoutManager=LinearLayoutManager(context)
        initData()
        initListener()
        return view
    }

    private fun initListener() {

    }

    private fun initData() {

        playCollectAdapter= PlayCollectAdapter()
        lifecycleScope.launch {
            var allPlayCollectListFlow = playCollectViewModel.getAllPlayCollectListFlow(1)
            allPlayCollectListFlow.collect{ lst->
                var list= ArrayList<SongInfoData>()
                lst.forEach {data->
                    list.add(SongInfoData(data.businessKey, data.bgImg,data.title,data.lrc,
                        data.url,data.singer,data.singerId,data.publishDate,data.albumId,data.albumName,null,0,null,null,null,null,null))

                }
                currentPlayLst=list
                playCollectAdapter.initData(list)
            }
        }
        playCollectAdapter.setOnItemClickListener(object : PlayCollectAdapter.OnItemClickListener {
            override fun onItemClick(data: SongInfoData, position: Int) {
                StartActivityUtils.startAudioPlayerActivityAndSaveDB(requireContext(), currentPlayLst,position)
            }
        })
        commonView.adapter=playCollectAdapter
    }


}